package com.sj.parksdk.fragment.profile;

import android.annotation.SuppressLint;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.setting.Extras;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;

import butterknife.BindView;

@Page(name = "扫码领券", params = {Extras.BASE_CODE})
public class FragmentReceiveCoupons extends BaseFragment {
    @BindView(R2.id.iv_state)
    ImageView ivState;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.btn_scan)
    SuperButton btnScan;

    @AutoWired(name = Extras.BASE_CODE)
    String couponsCode;

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_qrcode_success;
    }

    @Override
    protected void initViews() {
        ivState.setVisibility(View.INVISIBLE);
        if(StringUtils.isEmpty(couponsCode)){
            updateState(false,"暂无优惠券");
            return;
        }
        queryReciveCoupons();
    }

    @Override
    protected void initListeners() {
        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popToBack();
            }
        });
    }

    @SuppressLint("CheckResult")
    private void queryReciveCoupons() {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .receiveCoupons(couponsCode))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        if(result.getCode() == 200)updateState(true,"领券成功，请查看优惠券列表");
                        else updateState(false,result.getMessage());
                    }

                    @Override
                    public void onError(ApiException e) {
                        updateState(false,e.getMessage());
                    }
                });
    }

   private  void updateState(boolean success,String message){
       ivState.setVisibility(View.VISIBLE);
       tvContent.setText(message);
       ivState.setImageResource(success?R.drawable.park_ic_success :R.drawable.park_ic_error);
   }
}
